package com.fulu.netty.luban.forthdemo;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;


public class TestServerInitializer extends ChannelInitializer<SocketChannel>{

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // websocket基于http协议，所以要加入http编码和解码工具
        pipeline.addLast(new HttpServerCodec());
        // 对于大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        // 对于http消息进行聚合，聚合成FullHttpRequest或者FullHttpResponse
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        // 针对客户端，如果一分钟内没有向服务器发送读写心跳，则主动断开连接
        pipeline.addLast(new IdleStateHandler(40, 50, 45));
        // 自定义的读写状态监测
        pipeline.addLast(new HeartBeatHandler());
        // websocket支持
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new DelimiterBasedFrameDecoder(1024, Delimiters.lineDelimiter()));
        // 定义消息读取和发送的处理器
        pipeline.addLast(new ChatHandler());

    }
}
